<?php

namespace Home\Controller;

class UserController extends BaseMemberController {

    function _initialize() {
        parent::_initialize();
        $this->_Member_mod = M("Member");
        $this->_user_id = session('visitor.user_id');
//        $this->_user_id = 3;

    }

    /**
     * @api {get} /index.php?m=Home&c=User&a=index 用户信息接口
     */
    function index() {
        //统计页面-我的
        set_day_statistics_redis('view_my');
        $user_info = M('member')->where('user_id=' . $this->_user_id)->find();
        $user_info['ugrade'] = D('member')->get_grade_info($this->_user_id);
        $user_info['ugrade']['grade_name'] = $user_info['is_promoters'] == 1 ? '推广用户' : '普通用户';
        if (!$user_info) {
            render('10106', '用户不存在');
        }
        unset($user_info['password']);
        unset($user_info['zf_pass']);
        $resBanner = M('banner_setting')->where(array('type_id' => 4))->order('sort_order')->limit(5)->select();
        $data['banner'] = $resBanner;
        //获取订单数目信息
        $data['pending'] = M('order')->where("buyer_id = " . $this->_user_id . " AND status = '" . ORDER_PENDING . "'")->count("order_id");
        $data['accepted'] = M('order')->where("buyer_id = " . $this->_user_id . " AND status = '" . ORDER_ACCEPTED . "'")->count("order_id");
        $data['shipped'] = M('order')->where("buyer_id = " . $this->_user_id . " AND status = '" . ORDER_SHIPPED . "'")->count("order_id");
        $data['finished'] = M('order')->where("buyer_id = " . $this->_user_id . " AND status = '" . ORDER_FINISHED . "' AND evaluation_status = 0")->count("order_id");
        $resStore = M('store')->where(array('is_main' => 1))->field('store_id')->find();
        $user_info['store_id'] = $resStore['store_id'];
        $res_token = M('app_token')->where(array('user_id'=>$this->_user_id))->order('user_id desc')->find();
        if(!$res_token){
            render('10106', '用户不存在');
        }
        $invite_code = set_encrypt($this->_user_id);
        $url = C('SITE_URL').'/mobile/index.php?app=qrcode&act=download&invite_code='.$invite_code;
//        $url = C('SITE_URL').'/mobile/index.php?app=share&act=index&token='.$res_token['token'];
        $user_info['share_url'] = $url;
        $user_info['qrcode_url'] ? $user_info['qrcode_url'] = C('SITE_URL').$user_info['qrcode_url'] : '';
        $res_max_money = M('mall_config')->where(array('code'=>'withdraw_amount'))->find();
        $user_info['withdraw_amount'] = $res_max_money['value'];
//        if(!$user_info['qrcode_url']){
//            $qrcode = $this->get_qrcode($this->_user_id);
//            header('content-type:application/json');
//            $member_update = M('member')->where(array('user_id'=>$this->_user_id))->save(array('qrcode_url'=>$qrcode));
//            $user_info['qrcode_url'] = C('SITE_URL').$qrcode;
//        }else{
//            $user_info['qrcode_url'] = C('SITE_URL').$user_info['qrcode_url'];
//        }
        //是否为可获取个人推广注册链接的我方工作人员
        $info = M('promoters')->where(array("phone_mob"=>$user_info['phone_mob']))->find();
        $user_info['promoters'] = $info ? 1 : 0;

        render('10000', '', array_merge(array('order' => $data), $user_info));
    }


    /**
     * @api {get} /index.php?m=Home&c=User&a=profile 显示用户基本信息
     * 
     */
    function profile() {
        if (!IS_POST) {
            $member = $this->_Member_mod->where('user_id=' . $this->_user_id)->find();
            $textarea = M('textarea')->find();
            render('10000', '获取用户信息成功', array(
                'member' => $member,
                'textarea'=>$textarea['member']
            ));
        }
    }

    /**
     * @api {post} /index.php?m=Home&c=User&a=profile_edit 编辑用户基本信息
     * @apiName 编辑用户基本信息
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 编辑用户基本信息
     * 
     * @apiParam {String} real_name 真实姓名
     * @apiParam {String} gender 性别
     * @apiParam {String} birthday 生日
     * @apiParam {String} im_msn MSN帐号
     * @apiParam {String} im_qq QQ帐号
     */
    function profile_edit() {
        if (IS_POST) {
            $data = array(
                'real_name' => I('post.real_name', ''),
//                lichen 2019/6/5 start
                'user_no' => I('post.user_no', ''),
//                lichen 2019/6/5 end
                'gender' => I('post.gender', ''),
//                'birthday' => I('post.birthday', ''),
                'im_msn' => I('post.im_msn', ''),
                'im_qq' => I('post.im_qq', ''),
            );
            $this->_Member_mod->where('user_id=' . $this->_user_id)->save($data);
            render('10000', '编辑成功');
        }
    }

    /**
     * @api {post} /index.php?m=Home&c=User&a=password 设置用户登录密码
     * @apiName 设置用户登录密码
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 设置用户登录密码
     * 
     * @apiParam {String} orig_password 原密码
     * @apiParam {String} new_password 新密码
     * @apiParam {String} confirm_password 再次输入新密码
     * 
     */
    function password() {
        if (IS_POST) {
            $orig_password = I('post.orig_password', '');
            $new_password = I('post.new_password', '');
            $confirm_password = I('post.confirm_password', '');
            if ($new_password != $confirm_password) {
                render('10102', '输入两次密码不一致！');
            }
            if (!$new_password) {
                render('10105', '新密码为空！');
            }
            $passlen = strlen($new_password);
            if ($passlen < 6 || $passlen > 20) {
                render('10104', '密码长度必须大于6位！');
                return;
            }
            D("Member")->do_edit($this->_user_id, $orig_password, array('password' => $new_password));
            render('10000', '修改密码成功');
        }
    }
    
    

    /**
     * @api {post} /index.php?m=Home&c=User&a=mobile_edit 修改绑定手机
     * @apiName 修改绑定手机
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 修改绑定手机
     * 
     * @apiParam {String} msg_sign 短信签名
     * @apiParam {String} phone_mob 新手机
     * @apiParam {String} msg_code 验证码
     * 
     */
    function mobile_edit() {
        $msg_sign = I('request.msg_sign', '');
        $phone_mob = I('request.phone_mob', '');
        $msg_code = I('request.msg_code', '');
        if (empty($msg_sign) || empty($msg_code) || empty($phone_mob)) {
            render('10001', '缺少参数');
        }
        if (md5('send_message_change' . $msg_code) != $msg_sign) {
            render('10016', '短信验证码错误');
        }
        //判断此手机是否被绑定
        $member = M('member')->where('phone_mob=' . $phone_mob)->find();
        if(!empty($member)){
            render('19999', '对不起此手机已经被绑定');
        }
        $result = M('Member')->where('user_id=' . $this->_user_id)->save(array('phone_mob' => $phone_mob));
        if($result){
            render('10000', '修改支付密码成功');
        }else{
            render('19999', '修改支付密码失败');
        }
    }

    /**
     * 
     * @api {get} /index.php?m=Home&c=User&a=send_message_change 发送修改绑定手机的短信
     * @apiName 发送修改绑定手机的短信
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 发送修改绑定手机的短信
     * 
     * @apiParam {String} msg_sign 短信签名
     */
    function send_message_change() {
        //传phone_mob 表示发送到指定手机号中
        $mobile = I('request.phone_mob', '');
        if (!empty($mobile)) {
            if (!preg_match("/^1[34578]{1}\d{9}$/", $mobile)) {
                render('10069', '绑定手机号格式错误!');
            }
        } else {
            $member = M('member')->where('user_id=' . $this->_user_id)->find();
            $mobile = $member['phone_mob'];
            if (!$mobile) {
                render('10012', '手机号码为空');
            }
        }
        D('Msglog')->send_msg_system('change', $mobile);
        $msg_sign = md5('send_message_change' . $_SESSION['MobileConfirmCode']);
        render('10000', '短信发送成功!', array('msg_sign' => $msg_sign));
    }
    
    
    /**
     * @api {get} /index.php?m=Home&c=User&a=favorite_goods_list 显示收藏的商品列表
     * @apiName 显示收藏的商品列表
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 显示收藏的商品列表
     * 
     * @apiSuccess {String} goods_id 商品ID
     * @apiSuccess {String} default_image 商品图片
     * @apiSuccess {String} goods_name 商品名称
     * @apiSuccess {String} price 价格
     * @apiSuccess {String} add_time 收藏时间
     */
    function favorite_goods_list() {
//        $map['collect.type'] = 'goods';
//        $map['user_id'] = $this->_user_id;
//        $map['user_id'] = 3;
        $goods_mod = M("goods");
//        $goods_list = $goods_mod->alias('gl')->where($map)
//                ->field("gl.market_price,gl.brand,gl.goods_id,gl.default_image,gl.goods_name,gsp.price,collect.add_time,MAX(gsp.discount_price) as end_cost_price, MIN(gsp.discount_price) as first_cost_price,MAX(gsp.price) as end_price, MIN(gsp.price) as first_price,MAX(gsp.price) as end_cost_price, MIN(gsp.price) as first_cost_price,cc.store_id as sto_id,ifnull(cc.ico ,'') as ico,gl.*")
//                ->join('LEFT JOIN ' . C('DB_PREFIX') . 'collect as collect ON item_id = goods_id')
//                ->join('LEFT JOIN ' . C('DB_PREFIX') . 'goods_spec as gsp ON gl.goods_id = gsp.goods_id')
//                ->join('left join ecm_discount d on gl.goods_id = d.goods_id')
//                ->join('left join ecm_coupon_codes cc on d.coupon_codes_id = cc.id')
//                ->group('gl.goods_id')
//                ->page(I('request.page', 1, 'intval') . ',10')
//                ->select();
//        foreach ($goods_list as $key => $value) {
//            $goods_list[$key]['is_exist'] = D('goods')->get_isSaled($value['goods_id']);
//        }


        
        $list = M('goods')
            ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs,ecm_collect collect')
            ->field('g.brand,g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,g.times,g.market_price,gs.comments,g.add_time,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >5000.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >5000.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist, MAX(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >5000.00) then null else gsp.discount_price end) as end_discount_price, MIN(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >5000.00) then null else gsp.discount_price end) as first_discount_price,MAX(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >5000.00) then null else gsp.price end) as end_cost_price,MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >5000.00) then null else gsp.price end) as first_cost_price,ifnull(g.label ,"") as label,convert(MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >5000.00) then null else gsp.price end) * 10/g.market_price,decimal(10,1)) as discount')
            ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and collect.type= "goods" and collect.item_id = g.goods_id and collect.user_id ='.$this->_user_id)
            ->page(I('request.page', 1, 'intval') . ',10')
            ->group('g.goods_id')
            ->having('is_exist = "true"')
            ->buildSql();
        $goods_list = M('discount')->alias('d')
            ->field("cc.store_id as sto_id,ifnull(cc.ico ,'') as ico,gl.*")
            ->join('right join '.$list.' gl on d.goods_id = gl.goods_id')
            ->join('left join ecm_coupon_codes cc on d.coupon_codes_id = cc.id and cc.enabled = 1')
            ->group('gl.goods_id')
            ->select();

        if($_POST['token']){
            $res_token = M('app_token')->where(array('token'=>$_POST['token']))->find();
            $res_user = M('member')->where(array('user_id'=>$res_token['user_id']))->find();
        }
        foreach ($goods_list as $k => $v) {
            //年代
            if($v['times']) {
                $temp_times = substr($v['times'],2,strlen($v['times'])-1);
                $goods_list[$k]['times_label'] = (int)$temp_times <= 2015 ? '过季特卖': '';
            }else{
                $goods_list[$k]['times_label'] = '';
            }
            //折扣
            if($v['discount']) {
                if ($v['discount'] > 3.5 && $v['discount'] < 6){
                    $goods_list[$k]['discount_label'] = '折扣';
                }else if($v['discount'] < 3.5 && $v['discount'] > 0){
                    $goods_list[$k]['discount_label'] = '清仓';
                }else{
                    $goods_list[$k]['discount_label'] = '';
                }
            }else{
                $goods_list[$k]['discount_label'] = '';
            }
            if($v['label'] == '正常'){
                $goods_list[$k]['label'] = '';
            }
            $list_a = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
                ->field('gsp.spec_2,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >5000.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id='.$v['goods_id'])
                ->group('gsp.spec_2')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->select();
            $arr = array_column($list_a,'spec_2');
            //尺码排序
            //1.先把数字排前面
            $arr_num = $arr ? $this->array_number_second($arr) : array();
            sort($arr_num);
            //2.按照尺码表取数字
            $arr_str = M('size_order')->group('size_name')->order('size_order asc')->select();
            $arr_str ? $arra_str = array_column($arr_str,'size_name') : array();
            //按顺序取出
            $arrs = $this->array_sort_second($arra_str,$arr);
            //数组合并
            $goods_list[$k]['spec_2s'] = array_merge($arr_num,$arrs);
            $list_b = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
                ->field('gsp.spec_2,ss.stock_name,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >5000.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id='.$v['goods_id'])
                ->group('ss.storestock_id')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->select();
            //发货地排序
            $array_unset = $this->array_unset_second($list_b,'stock_name');
            $arr = array_column($array_unset,'stock_name');
            $arrv = $this->array_sort_second(array( 0 => '境内仓',
                1 => '天津保税仓',
                2 => '香港直邮仓',
                3 => '海外直邮仓'),$arr);
            $goods_list[$k]['stock_names'] = $arrv;
            if ($v['sto_id'] && $_POST['token'] && $res_user){
                $res_store_goods = M('store')->where(array('store_id'=>$v['sto_id']))->find();
                $res_store_user = M('store')->where(array('store_id'=>$res_user['s_id']))->find();
                $res_region_goods = M('region')->where(array('region_id'=>$res_store_goods['region_id']))->find();
                $res_region_user = M('region')->where(array('region_id'=>$res_store_user['region_id']))->find();
                if($res_region_user['region_id'] == $res_region_goods['region_id'] || $res_region_user['parent_id'] == $res_region_goods['region_id'] || $res_region_user['region_id'] == $res_region_goods['parent_id']){
                    //显示优惠价
                    $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
                    $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                }else{
                    //显示普通价
                    $goods_list[$k]['first_price'] = $v['first_cost_price'];
                    $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                    $goods_list[$k]['ico'] = '';
                }
            }else if(strlen($v['sto_id']) && $v['sto_id'] == '0'){
                //显示优惠价
                $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
                $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
            }else{
                //显示普通价
                $goods_list[$k]['first_price'] = $v['first_cost_price'];
                $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                $goods_list[$k]['ico'] = '';
            }
        }

        if($_POST['user_id']){
            $cond_collect['user_id'] = $_POST['user_id'];
            $res_collect = M('collect')->where($cond_collect)->field('item_id as goods_id ,user_id')->select();
            foreach ($goods_list as $key => $goods) {
                $goods_list[$key]['add_time'] = date('Y-m-d H:i:s',$goods['add_time']);
                $res_spec = M('goods_spec')->group('spec_1value')->where(array('goods_id'=>$goods['goods_id']))->field('spec_1')->select();
                $data = array_column($res_spec,'spec_1');
                $goods_list[$key]['spec'] = $data;
                if($res_collect){
                    if(in_array($goods_list[$key]['goods_id'],array_column($res_collect,'goods_id'))){
                        $goods_list[$key]['collect'] = true;
                    }else{
                        $goods_list[$key]['collect'] = false;
                    }
                }else{
                    $goods_list[$key]['collect'] = false;
                }
            }
        }else{
            foreach ($goods_list as $key => $value){
                $res_spec = M('goods_spec')->group('spec_1value')->where(array('goods_id'=>$value['goods_id']))->field('spec_1')->select();
                $data = array_column($res_spec,'spec_1');
                $goods_list[$key]['spec'] = $data;
            }
        }
        render('10000', '获取收藏商品成功', array(
            'goods_list' => $goods_list
        ));
    }
    /**
     * @api {get} /index.php?m=Home&c=User&a=favorite_store_add 新增收藏的商品
     * @apiName 新增收藏的商品
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 新增收藏的商品
     * 
     * @apiParam {String} item_id 商品ID
     */
    function favorite_goods_add() {
        $item_id = I('request.item_id', 0, 'intval');
        if (empty($item_id)) {
            render('10001', '缺少参数');
        }
        $collect_mod = M("collect");
        $map['item_id'] = $item_id;
        $map['user_id'] = $this->_user_id;
        $map['type'] = 'goods';
        if ($collect_mod->where($map)->find()) {
            $collect_mod->where($map)->delete();
            render('10000', '删除商品成功');
        }
        $map['add_time'] = time();
        $collect_mod->add($map);
        render('10000', '收藏商品成功');
    }
    
    /**
     * @api {get} /index.php?m=Home&c=User&a=favorite_goods_del 删除收藏的商品
     * @apiName 删除收藏的商品
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 删除收藏的商品
     * 
     * @apiParam {String} item_id 收藏ID
     * 
     */
    function favorite_goods_del() {
        $item_id = I('request.item_id', 0, 'intval');
        if (empty($item_id)) {
            render('16666', '参数错误');
        }
        $collect_mod = M("collect");
        $map['item_id'] = $item_id;
        $map['user_id'] = $this->_user_id;
        $map['type'] = 'goods';
        $collect_mod->where($map)->delete();
        render('10000', '删除收藏商品成功');
    }

    /**
     * @api {get} /index.php?m=Home&c=User&a=favorite_store_list 显示收藏的店铺列表
     * @apiName 显示收藏的店铺列表
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 显示收藏的店铺列表
     * 
     * @apiSuccess {String} store_id 店铺ID
     * @apiSuccess {String} store_logo 店铺LOGO
     * @apiSuccess {String} store_name 店铺名称
     * @apiSuccess {String} owner_name 拥有者名称
     * @apiSuccess {String} add_time 收藏时间
     * 
     */
    function favorite_store_list() {
        $map['user_id'] = $this->_user_id;
        $map['collect.type'] = 'store';
        $store_mod = M("store");
        $store_list = $store_mod->where($map)
                ->field('store_id,store_logo,store_name,owner_name,collect.add_time')
                ->join('LEFT JOIN ' . C('DB_PREFIX') . 'collect as collect ON item_id = store_id')
                ->page(I('request.page', 1, 'intval') . ',10')
                ->select();
        
        if($store_list){
            foreach ($store_list as $key => $store) {
                $store_list[$key]['add_time'] = date('Y-m-d H:i:s',$store['add_time']);
            }
        }
        
        render('10000', '获取收藏店铺成功', array(
            'store_list' => $store_list,
        ));
    }

    /**
     * @api {get} /index.php?m=Home&c=User&a=favorite_store_add 新增收藏的店铺
     * @apiName 新增收藏的店铺
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 新增收藏的店铺
     * 
     * @apiParam {String} item_id 店铺ID
     * 
     */
    function favorite_store_add() {
        $item_id = I('request.item_id', 0, 'intval');
        if (empty($item_id)) {
            render('10001', '缺少参数');
        }
        $collect_mod = M("collect");
        $map['item_id'] = $item_id;
        $map['user_id'] = $this->_user_id;
        $map['type'] = 'store';
        if ($collect_mod->where($map)->find()) {
            render('10121', '已收藏过该店铺');
        }
        $map['add_time'] = time();
        $collect_mod->add($map);
        render('10000', '收藏店铺成功');
    }

    /**
     * @api {get} /index.php?m=Home&c=User&a=favorite_store_del 删除收藏的店铺
     * @apiName 删除收藏的店铺
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 删除收藏的店铺
     * 
     * @apiParam {String} item_id 店铺ID
     * 
     */
    function favorite_store_del() {
        $item_id = I('request.item_id', 0, 'intval');
        if (empty($item_id)) {
            render('10001', '缺少参数');
        }
        $collect_mod = M("collect");
        $map['item_id'] = $item_id;
        $map['user_id'] = $this->_user_id;
        $map['type'] = 'store';
        $collect_mod->where($map)->delete();
        render('10000', '删除收藏店铺成功');
    }

    /**
     * @api {get} /index.php?m=Home&c=User&a=address_list 显示用户地址列表
     * @apiName 显示用户地址列表
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 显示用户地址列表
     * 
     * @apiSuccess {String} addr_id 地址ID
     * @apiSuccess {String} user_id 用户ID
     * @apiSuccess {String} consignee 收货人
     * @apiSuccess {String} region_id 地区ID
     * @apiSuccess {String} region_name 地区名称
     * @apiSuccess {String} address 详细地址
     * @apiSuccess {String} zipcode 邮政编码
     * @apiSuccess {String} phone_mob 联系手机
     * @apiSuccess {String} is_default 是否为默认地址1为是  0 为否 
     */
    function address_list() {
        $address_mod = M("address");
        $map['user_id'] = $this->_user_id;
        $address_list = $address_mod
                ->where($map)
                ->order('is_default desc')
                ->page(I('request.page', 1, 'intval') . ',10')
                ->select();
        $textarea = M('textarea')->find();
        render('10000', '获取地址列表成功', array(
            'address_list' => $address_list,
            'textarea' => $textarea['address']
        ));
    }

    /**
     * @api {post} /index.php?m=Home&c=User&a=address_add 新增地址
     * @apiName 新增地址
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 新增地址
     * 
     * @apiParam {String} consignee 收货人
     * @apiParam {String} region_id 地区ID
     * @apiParam {String} region_name 地区名称
     * @apiParam {String} address 详细地址
     * @apiParam {String} zipcode 邮政编码
     * @apiParam {String} phone_mob 联系手机
     * 
     */
    function address_add() {
        if (IS_POST) {
            $address_mod = M("address");
            $address_mod -> startTrans();
            if(I('post.is_default') == 1){
                $res = $address_mod->where(array('user_id'=>$this->_user_id))->save(array('is_default'=>0));
                if($res === false){
                    $address_mod -> rollback();
                    render('10004','设置失败');
                }
            }
            if(!$this->is_idcard(I('post.user_no')) && I('post.user_no')){
                render('16666', '身份证号格式错误');
            }
            $data = array(
                'user_id' => $this->_user_id,
                'consignee' => I('post.consignee'),
                'region_id' => I('post.region_id'),
                'region_name' => I('post.region_name'),
                'user_no' => I('post.user_no'),
                'address' => I('post.address'),
                'zipcode' => I('post.zipcode'),
                'phone_mob' => I('post.phone_mob'),
                'is_default' => I('post.is_default'),
            );
            $res_add = $address_mod->data($data)->add();
            if(!$res_add){
                $address_mod -> rollback();
                render('10004','新增失败');
            }
            $address_mod -> commit();
            render('10000','新增成功');
        }
    }

    /**
     * @api {post} /index.php?m=Home&c=User&a=address_edit 编辑地址
     * @apiName 编辑地址
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 编辑地址
     * 
     * @apiParam {String} addr_id 地址ID
     * @apiParam {String} consignee 收货人
     * @apiParam {String} region_id 地区ID
     * @apiParam {String} region_name 地区名称
     * @apiParam {String} address 详细地址
     * @apiParam {String} zipcode 邮政编码
     * @apiParam {String} phone_mob 联系手机
     * 
     */
    function address_edit() {
        $addr_id = I('request.addr_id', 0, 'intval');
        if (empty($addr_id)) {
            render('16666', '参数错误');
        }
        $address_mod = M("address");
        $map['user_id'] = $this->_user_id;
        $map['addr_id'] = $addr_id;

        $address = $address_mod->where($map)->find();
        if (empty($address)) {
            render('16666', '地址不存在');
        }

        if (IS_POST) {
            $address_mod -> startTrans();
            if(I('post.is_default') == 1){
                $rs = $address_mod->where("user_id=" . $this->_user_id)->save(array('is_default'=>0));
                if($rs === false){
                    $address_mod -> rollback();
                    render('10004','设置失败');
                }
                $res = $address_mod->where(array('addr_id'=>$addr_id))->save(array('is_default'=>1));
                if($res === false){
                    $address_mod -> rollback();
                    render('10004','设置失败');
                }
            }
            if(!$this->is_idcard(I('post.user_no')) && I('post.user_no')){
                render('16666', '身份证号格式错误');
            }
            $data = array(
                'is_default' => I('post.is_default'),
                'consignee' => I('post.consignee'),
                'region_id' => I('post.region_id'),
                'region_name' => I('post.region_name'),
                'address' => I('post.address'),
                'user_no' => I('post.user_no'),
                'zipcode' => I('post.zipcode'),
                'phone_mob' => I('post.phone_mob'),
            );
            $res_add = $address_mod->where($map)->save($data);
            if($res_add === false){
                $address_mod -> rollback();
                render('10004','修改失败');
            }
            $address_mod -> commit();
            render('10000', '修改地址成功');
        } else {
            render('10000', '获取地址成功', array('address' => $address));
        }
    }
    /**
     * @api {post} /index.php?m=Home&c=User&a=set_default_address 设置默认收货地址
     * @apiName 设置默认收货地址
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 设置默认收货地址
     * 
     * @apiParam {String} addr_id 地址ID
     */
    function set_default_address()
    {
        $addr_id = I('request.addr_id', 0, 'intval');
        if (empty($addr_id)) {
            render('16666', '参数错误');
        }
        $address_mod = M("address");
        $map['user_id'] = $this->_user_id;
        $map['addr_id'] = $addr_id;
        
        $address_mod->where("user_id=" . $this->_user_id)->save(array('is_default'=>0));
        $address_mod->where("addr_id = {$addr_id} AND user_id=" . $this->_user_id)->save(array('is_default'=>1));
        render('10000', '设置默认地址成功');
    }
    /**
     * @api {post} /index.php?m=Home&c=User&a=address_del 删除地址
     * @apiName 删除地址
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 删除地址
     * 
     * @apiParam {String} addr_id 地址ID
     */
    function address_del() {
        $addr_id = I('request.addr_id', 0, 'intval');
        if (empty($addr_id)) {
            render('16666', '参数错误');
        }
        $address_mod = M("address");
        $map['user_id'] = $this->_user_id;
        $map['addr_id'] = $addr_id;
        $address = $address_mod->where($map)->find();
        if (empty($address)) {
            render('16666', '地址不存在');
        } else {
            $address_mod->where($map)->delete();
            render('10000', '');
        }
    }

//    lichen 2019/5/27 start
    function upload_portrait(){
        if(empty($_POST['user_id']) || empty($_POST['portrait'])){
            render('16666', '参数错误');
        }
        $url = M('Member')->where(array('user_id'=>$_POST['user_id']))->getField('portrait');
        if($url){
            $filename = './'.$url;
            unlink($filename);
        }
        $image = $_POST['portrait'];
        $imageName = date("YmdHis", time()) . rand(1000,10000) .'.jpg';
        if (strstr($image,",")){
            $image = explode(',',$image);
            $image = $image[1];
        }
        $path = BASE_PATH.'/data/files/mall/portrait/'. ceil($_POST['user_id'] / 500) . '/' .$_POST['user_id'];
        if (!is_dir($path)){ //判断目录是否存在 不存在就创建
            mkdir($path,0777,true);
        }
        $r = file_put_contents($path.'/'.$imageName, base64_decode($image));//返回的是字节数
        if (!$r) {
            render('16666', '图片生成失败');
        }else{
            $res = M('member')->where(array('user_id'=>$_POST['user_id']))->save(array('portrait'=>'data/files/mall/portrait/'. ceil($_POST['user_id'] / 500) . '/' .$_POST['user_id'].'/'.$imageName));
            if(!$res){
                render('16666', '上传失败');
            }
            render('10000', '图片生成成功',array('portrait'=>'data/files/mall/portrait/'. ceil($_POST['user_id'] / 500) . '/' .$_POST['user_id'].'/'.$imageName));
        }
    }

    function is_idcard( $id ){
        $id = strtoupper($id);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = array();
        if(!preg_match($regx, $id))
        {
            return FALSE;
        }
        if(15==strlen($id)) //检查15位
        {
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

            @preg_match($regx, $id, $arr_split);
            //检查生日日期是否正确
            $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth))
            {
                return FALSE;
            } else {
                return TRUE;
            }
        }
        else      //检查18位
        {
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $id, $arr_split);
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth)) //检查生日日期是否正确
            {
                return FALSE;
            }
            else
            {
                //检验18位身份证的校验码是否正确。
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                $sign = 0;
                for ( $i = 0; $i < 17; $i++ )
                {
                    $b = (int) $id{$i};
                    $w = $arr_int[$i];
                    $sign += $b * $w;
                }
                $n = $sign % 11;
                $val_num = $arr_ch[$n];
                if ($val_num != substr($id,17, 1))
                {
                    return FALSE;
                } //phpfensi.com
                else
                {
                    return TRUE;
                }
            }
        }

    }

    function array_number_second($arr){
        $tmp_arr = array();
        foreach($arr as $k => $v)
        {
            if(is_numeric($v)){
                $tmp_arr[] = $v;
            }
        }

        return $tmp_arr;
    }

    function array_unset_second($arr,$key){
        $tmp_arr = array();
        foreach($arr as $k => $v)
        {
            if(in_array($v[$key], $tmp_arr) || !$v[$key])   //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            {
                unset($arr[$k]); //销毁一个变量  如果$tmp_arr中已存在相同的值就删除该值
            }
            else {
                $tmp_arr[$k] = $v[$key];  //将不同的值放在该数组中保存
            }
        }
        //ksort($arr); //ksort函数对数组进行排序(保留原键值key)  sort为不保留key值
        return $arr;
    }

    function array_sort_second($arr1,$arr2){
        $c = array();
        for ($i = 0; $i < count($arr1); $i++) {
            for ($j = 0; $j < count($arr2); $j++) {
                if ($arr2[$j] == $arr1[$i]) {
                    $c[$i] = $arr2[$j];
                }
            }
        }
        return array_values($c);
    }

    /**
     * @api {post} /index.php?m=Home&c=User&a=get_user_qrcode 生成二维码
     */
    function get_user_qrcode(){
        $address = $this->get_qrcode($this->_user_id);
        header('content-type:application/json');
        $member_update = M('member')->where(array('user_id'=>$this->_user_id))->save(array('qrcode_url'=>$address));
        $data['qrcode_url'] = C('SITE_URL').$address;
        render('10000', '获取成功',$data);
    }

    function get_qrcode($user_id){
        vendor('phpqrcode.phpqrcode');
        $url1 = C('SITE_URL').'data/files/qrcode/background.png';
//        $url = C('SITE_URL').'mobile/index.php?app=qrcode&act=download&invite_code='.set_encrypt($user_id);

        $folder = dirname(dirname(dirname(dirname(__DIR__)))).'/data/files/users/user0'.$user_id;
        mkdirs($folder);
//        $path = $folder.'/qrcode_'.$user_id.'.png';
        $url2 = $folder.'/qrcode_'.$user_id.'.png';
//        $this->make_thumb($path,$url2,97);
//        $this->set_qrcode($url,$path);
        $this->get_wx_qrcode($user_id);
        $rs = mergeImage($url1,$url2,$folder.'/new_qrcode_'.$user_id.'.png');
        return 'data/files/users/user0'.$user_id.'/new_qrcode_'.$user_id.'.png';
    }

    function set_qrcode($url,$path){
//        $folder =  dirname(dirname(__DIR__)).'/Runtime/Logs/qrcode.png';
        vendor('phpqrcode.phpqrcode');
        $QRcode = new \Qrcode();
        $value = $url;
        $errorCorrectionLevel = "L";
        $matrixPointSize = "2.9";
        $rs = $QRcode::png($value, $path, $errorCorrectionLevel, $matrixPointSize,0, TRUE);
    }
    function get_wx_qrcode($user_id)
    {
//        $file = '../data/files/wx_applet_store/store_'.$store_id.'/'.$file_name;
        $appid = C('app_jsapi_appid');
        $secret = C('app_jsapi_appsecret');

        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
        // get请求获取access_token
        $data = request_get($url);
        $data = json_decode($data, true);
        $msg = '获取微信access_token失败';
        if ($data['access_token']) {
            //获取二维码
            //参数
            $postdata['scene'] = 'invite_code=' . set_encrypt($user_id);
            // 宽度
            $postdata['width'] = 280;
            // 页面
            $postdata['page'] = 'pages/promotion/couponreg';
            // 线条颜色
            $postdata['auto_color'] = false;
            //auto_color 为 false 时生效
            $postdata['line_color'] = array('r' => '0', 'g' => '0', 'b' => '0');
            // 是否有底色为true时是透明的
            $postdata['is_hyaline'] = false;

            // 获取二维码
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $data['access_token'];
            // post请求
            $postdata = json_encode($postdata);
            $result=request_post($url,$postdata);
            $data = file_get_contents("php://input");
            // 保存二维码
            $folder = dirname(dirname(dirname(dirname(__DIR__)))) . '/data/files/users/user0' . $user_id;
            mkdirs($folder);
            $res1 = file_put_contents($folder.'/qrcode_'.$user_id.'.png', $result, true);//使用函数file_put_contents()进行重新写入文件，与依次调用 fopen()，fwrite() 以及 fclose() 功能一样。
            return $folder;  //这个就是你要保存的图片格式文件
        }
    }


}

